<template>
    <div class="base">
        <div class="left">
            <el-button class="menu" @click="initCamera">监测</el-button>
            <el-button class="menu" @click="stopcamera">停止</el-button>
            <button class="menu" @click="snap">截图对比人脸</button>
        </div>
        <video ref="video" autoplay v-if="autoplay"></video>
        <canvas ref="canvas" v-if="autoplay" width="640" height="480"></canvas>
        <!-- <div v-else>请点击监测</div> -->
    </div>
</template>

<script>
export default {
    data() {
        return {
            autoplay: false
        };
    },

    mounted() {
    },
    methods: {

        uploadImage(base64) {
            // 将Base64字符串转换为Blob对象
            let byteCharacters = atob(base64.split(',')[1]);
            let byteNumbers = new Array(byteCharacters.length);
            for (let i = 0; i < byteCharacters.length; i++) {
                byteNumbers[i] = byteCharacters.charCodeAt(i);
            }
            let byteArray = new Uint8Array(byteNumbers);
            let blob = new Blob([byteArray], { type: 'image/png' });

            // 创建FormData对象并添加文件
            let formData = new FormData();
            formData.append('file', blob, 'image.png');

            // 发送POST请求到服务器
            this.$axios.post('http://localhost:8080/user/faceLogin', formData, {
                headers: {
                    'Content-Type': 'multipart/form-data',
                    'token': localStorage.getItem('token')
                }
            }).then(response => {
                console.log(response);
                if (response.data.score > 0.67) {
                    this.$message.success('是同一个人');
                } else {
                    this.$message.error('不是同一个人');
                }
            }).catch(error => {
                console.log(error);
            });
        },
        snap() {
            this.$refs.canvas.getContext('2d').drawImage(this.$refs.video, 0, 0, 640, 480);
            console.log(this.$refs.canvas.toDataURL());
            this.uploadImage(this.$refs.canvas.toDataURL())
        },
        async stopcamera() {
            this.autoplay = false
            window.location.reload();
        },
        hello() {
            console.log('hello');
        },
        async initCamera() {
            this.autoplay = true
            try {
                let stream = await navigator.mediaDevices.getUserMedia({ video: true });
                this.$refs.video.srcObject = stream;
            } catch (error) {
                console.error('Error accessing camera:', error);
            }

        },
    },
};
</script>
<style scoped>
.base {
    display: flex;
    flex-direction: row;
}

.left {
    width: 200px;
    height: 98vh;
    background-color: beige;
    display: flex;
    flex-direction: column;
    align-items: center;
}

.menu {
    margin-top: 20px;
    margin-left: 0;
}

.right {
    height: 98vh;
    flex: 2;
    display: flex;
    flex-direction: column;
}
</style>